package com.link.play.fit.ai.ui.guide

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.databinding.FgAccountBinding
import com.link.play.fit.ai.kv.AuthCache.isInitGuide
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.signInGoogle
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.MainViewModel
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import kotlinx.coroutines.launch


class AccountFg : BasePageFragment<FgAccountBinding>(FgAccountBinding::inflate) {
    private val viewModel: MainViewModel by lazy {
        ViewModelProvider(this)[MainViewModel::class.java]
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.tvSkip.setOnClickListener {
            saveUserGuide()
            goToAc(MainAc::class.java)
            requireActivity().finish()
        }
        binding.llSign.setOnClickListener {
            lifecycleScope.launch {
                val result = activity?.signInGoogle() ?: false
                if (result) {
                    Toast.makeText(
                        context,
                        getString(R.string.sign_in_successful),
                        Toast.LENGTH_SHORT
                    ).show()
                    saveUserGuide()
                    goToAc(MainAc::class.java)
                    requireActivity().finish()
                }
            }
        }
    }

    private fun saveUserGuide() {
        isInitGuide = true
        val userGuideState = (requireActivity() as GuidePbAc).viewModel.userGuideState.value
        userGuideState.haveWeighControlPlan = RemoteConfig.isWeightControlGuide && (userGuideState.needPersonalTrain == 1)
        //保存引导数据的信息
        CloudStore.set(CloudStore.DOC_USER_GUIDE, userGuideState)
        //保存当天的体重记录
        CloudStore.addToList(
            DOC_LOG_WEIGHT,
            DOC_LOG_WEIGHT,
            getDayOfMonth(),
            LogWeightBean(userGuideState.weightKg, userGuideState.weightLbs)
        )
    }

}